import 'package:mysql1/mysql1.dart';
import 'package:accept_form/models/user.dart';

class UserService {
  static final UserService instance = UserService._internal();
  MySqlConnection? _connection;

  UserService._internal();

  Future<MySqlConnection> _getConnection() async {
    if (_connection == null || _connection!.isClosed) {
      final settings = ConnectionSettings(
        host: 'localhost',
        port: 3306,
        db: 'accept',
        user: 'root',
        password: '',
      );
      _connection = await MySqlConnection.connect(settings);
    }
    return _connection!;
  }

  Future<void> close() async {
    if (_connection != null && !_connection!.isClosed) {
      await _connection!.close();
    }
  }

  Future<List<User>> getUsers() async {
    final conn = await _getConnection();
    final results = await conn.query('SELECT * FROM users ORDER BY id');
    return results.map((row) => User.fromJson(row.fields)).toList();
  }

  Future<User> createUser({
    required String username,
    required String password,
    required String realName,
    String? email,
    String? phone,
  }) async {
    final conn = await _getConnection();
    final result = await conn.query(
      'INSERT INTO users (username, password, real_name, email, phone, status) VALUES (?, ?, ?, ?, ?, 1)',
      [username, password, realName, email, phone],
    );
    final id = result.insertId!;
    return User(
      id: id,
      username: username,
      name: realName,
      email: email,
      phone: phone,
      role: 'user',
    );
  }

  Future<void> updateUser({
    required int id,
    String? realName,
    String? email,
    String? phone,
  }) async {
    final conn = await _getConnection();
    final updates = <String>[];
    final values = <dynamic>[];

    if (realName != null) {
      updates.add('real_name = ?');
      values.add(realName);
    }
    if (email != null) {
      updates.add('email = ?');
      values.add(email);
    }
    if (phone != null) {
      updates.add('phone = ?');
      values.add(phone);
    }

    if (updates.isNotEmpty) {
      values.add(id);
      await conn.query(
        'UPDATE users SET ${updates.join(', ')} WHERE id = ?',
        values,
      );
    }
  }

  Future<void> deleteUser(int id) async {
    final conn = await _getConnection();
    await conn.query('DELETE FROM users WHERE id = ?', [id]);
  }
} 